<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style></style>
  </head>
  <body>
    <div>Generator(生成器函数)异步方案(下)</div>
    <script>
      function ajax(url) {
        return new Promise((resolve, reject) => {
          let xhr = new XMLHttpRequest();
          xhr.open("GET", url);
          xhr.responseText = "json";
          xhr.onload = function () {
            if (this.status === 200) {
              resolve(this.response);
            } else {
              reject(new Error(this.statusText));
            }
          };
          xhr.send();
        });
      }

      function* main() {
        try {
          const users = yield ajax("/asyn/user.json");
          console.log(users);
          const users2 = yield ajax("/asyn/user.json");
          console.log(users2);
          const users3 = yield ajax("/asyn/user3.json");
          console.log(users3);
        } catch (e) {
          console.log(e);
        }
      }

      function co(generator) {
        //得到一个生成器函数
        const g = generator();
        function handliResult(result) {
          if (result.done) result; //生成器函数结束
          result.value.then(
            (data) => {
              handliResult(g.next(data));
            },
            (err) => {
              g.throw(err);
            }
          );
        }
        handliResult(g.next());
      }

      co(main);
    </script>
  </body>
</html>
